// SPDX-License-Identifier: GPL-2.0
/*
 * Copyright (C) 2020-2021, LomboTech Co.Ltd.
 * Author: lomboswer <lomboswer@lombotech.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/dma-mapping.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/of_reserved_mem.h>
#include <linux/dma-mapping.h>

#define MAX_ALLOC_SIZE		0x800

static void *virt_addr;
static dma_addr_t phys_addr;

static const struct of_device_id coherent_interface_match[] = {
	{ .compatible = "lombo, coherent_mem_test", },
	{},
};
MODULE_DEVICE_TABLE(of, coherent_interface_match);

static int coherent_interface_probe(struct platform_device *pdev)
{
	int ret;
	int i = 0;
	int count = 0;

	ret = of_reserved_mem_device_init(&pdev->dev);
	if (ret < 0) {
		pr_warn("%s:%d, bindding device to coherent memroy failed\n",
			__func__, __LINE__);
	}

	virt_addr = dma_alloc_coherent(&pdev->dev,
			MAX_ALLOC_SIZE,
			&phys_addr,
			0);

	for (i = 0; i < (MAX_ALLOC_SIZE) / sizeof(unsigned int); ++i)
		*(((unsigned int *)virt_addr) + i) = ++count;

	return 0;
}

static int coherent_interface_remove(struct platform_device *pdev)
{
	dma_free_coherent(&pdev->dev, MAX_ALLOC_SIZE, virt_addr, phys_addr);

	of_reserved_mem_device_release(&pdev->dev);

	return 0;
}

static struct platform_driver coherent_interface_driver = {
	.probe  = coherent_interface_probe,
	.remove = coherent_interface_remove,
	.driver = {
		.name  = "coherent_mem_test",
		.owner = THIS_MODULE,
		.of_match_table = coherent_interface_match,
	},
};

static int __init coherent_interface_init(void)
{
	return platform_driver_register(&coherent_interface_driver);
}
module_init(coherent_interface_init);

MODULE_DESCRIPTION("LomboTech coherent interface test Driver");
MODULE_AUTHOR("LomboTech Co.Ltd");
MODULE_LICENSE("GPL");
